<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools show-before>
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="danger"
            @click="expotrExcel(false)"
          >简单excel导出</el-button>
          <el-button size="small" type="info" @click="expotrExcel(true)">复杂excel导出</el-button>
          <el-button
            size="small"
            type="success"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            size="small"
            type="primary"
            @click="addEmployee"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="employeeList" stripe>
          <el-table-column
            label="序号"
            sortable=""
            type="index"
            width="80px"
            align="center"
          />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" prop="staffPhoto">
            <template v-slot="{ row }">
              <img
                v-imageError="require('@/assets/common/avator.png')"
                :src="row.staffPhoto"
                style="width: 100px; height: 100px; border-radius: 50%"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployement"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            background
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>

    <AddEmployee :show-dialog="showDialog" />
    <el-dialog title="扫码预览" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  components: {
    AddEmployee
  },

  data() {
    return {
      EmployeeEnum, // 枚举
      employeeList: [],
      page: {
        page: 1,
        size: 10
      },

      loading: false,
      showDialog: false,
      showCodeDialog: false
    }
  },

  created() {
    this.getEmployeeList()
  },

  methods: {
    // 获取员工列表
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.employeeList = rows
      this.page.total = total
      await new Promise((resolve) => setTimeout(() => resolve(), 100))
      this.loading = false
    },

    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },

    // 格式化聘用形式
    formatEmployement(row, column, cellValue, index) {
      const obj = this.EmployeeEnum.hireType.find(
        (item) => item.id + '' === cellValue
      )
      return obj ? obj.value : '未知'
    },

    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确定要删除该员工吗？')
        await delEmployee(id)

        if (this.employeeList.length === 1) {
          this.page.page--
        }
        this.$message.success('删除员工成功！')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },

    // 新增员工
    addEmployee() {
      this.showDialog = true
    },

    // 导出excel
    expotrExcel(isComplex) {
      console.log(isComplex)
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 该模块已经动态导入
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        const data = this.formaatJson(headers, rows)
        const multiHeader = isComplex ? [['姓名', '主要信息', '', '', '', '', '部门']] : []
        const merges = isComplex ? ['A1:A2', 'B1:F1', 'G1:G2'] : []
        console.log(multiHeader, merges)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          multiHeader, // 复杂表头
          merges, // 合并行列
          data, // 具体数据 必填
          filename: '人力资源表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },

    // 格式化JSON数据 --- [{}, {}, {}] => [[], [], []]
    formaatJson(headers, rows) {
      return rows.map((item) => {
        // item - 每一个对象 {}
        return Object.values(headers).map((value) => {
          // value - 每一个英文字段名

          if (value === 'formOfEmployment') {
            const obj = this.EmployeeEnum.hireType.find(
              (o) => o.id + '' === item[value]
            )
            return obj ? obj.value : '未知'
          } else if (value === 'timeOfEntry' || value === 'correctionTime') {
            return formatDate(item[value])
          }
          return item[value]
        })
      })
    },

    // 二维码
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => QrCode.toCanvas(this.$refs.myCanvas, url))
      } else {
        this.$message.warning('您还未上传头像')
      }
    }
  }
}
</script>
